﻿using LDM.Framework.Application;
using LDM.Framework.ExceptionHandling;
using LDM.Framework.NormalizeActionResult;
using Microsoft.Extensions.DependencyInjection;
using System.Net;
using Utility.Helpers;
using WebApiClientCore;
using WebApiClientCore.Attributes;

namespace LDM.Framework.WebApiClientCore;

/// <summary>
/// 
/// </summary>
//[AttributeUsage(AttributeTargets.Interface)]
public class HttpApiOptionsAttribute : ApiFilterAttribute
{
    /// <summary>
    /// 
    /// </summary>
    public string Path { get; set; }

    /// <summary>
    /// ctor
    /// </summary>
    /// <param name="path"></param>
    public HttpApiOptionsAttribute(string path)
    {
        Path = path;
    }

    /// <summary>
    /// 请求拦截
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task OnRequestAsync(ApiRequestContext context)
    {
        var options = context.HttpContext.HttpApiOptions;
        //获取注册时为服务配置的服务名
        var consulLoad = System.Convert.ToBoolean(App.Configuration["Consul:ConsulLoad"]);
        if (!consulLoad)
            return Task.CompletedTask;
        IServiceProvider sp = context.HttpContext.ServiceProvider;
        HostProvider hostProvider = sp.GetRequiredService<HostProvider>();
        string host = hostProvider.ResolveService(Path);
        HttpApiRequestMessage requestMessage = context.HttpContext.RequestMessage;
        //和原有的Uri组合并覆盖原有Uri
        //并非一定要这样实现，只要覆盖了RequestUri,即完成了替换
        requestMessage.RequestUri = requestMessage.MakeRequestUri(new Uri(host));
        var token = GetToken();
        if (!string.IsNullOrEmpty(token))
            context.HttpContext.RequestMessage.Headers.Add("Authorization", $"Bearer {token}");
        return Task.CompletedTask;
    }

    /// <summary>
    /// Gets the token.
    /// </summary>
    /// <returns>System.String.</returns>
    public static string GetToken()
    {
        if (Web.Request.Query.ContainsKey("token"))
        {
            return Web.Request.Query["token"].ToString();
        }

        if (Web.Request.Headers.ContainsKey("Authorization"))
        {
            var auth = Web.Request.Headers["Authorization"].ToString();
            if (auth.Contains("Bearer ", StringComparison.OrdinalIgnoreCase))
            {
                return auth.Substring("Bearer ".Length);
            }
        }
        if (Web.Request.Cookies.ContainsKey("Authorization"))
        {
            return Web.Request.Cookies["Authorization"];
        }
        return null;
    }




    /// <summary>
    /// 响应拦截
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override async Task<Task> OnResponseAsync(ApiResponseContext context)
    {
        ///处理错误码400时的异常向上抛出
        if (context.ResultStatus == ResultStatus.HasException &&
           context?.HttpContext?.ResponseMessage?.StatusCode == HttpStatusCode.BadRequest)
        {
            var msg = await context.HttpContext.ResponseMessage.Content.ReadAsStringAsync();
            if (msg != null)
            {
                var resultData = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultData>(msg);
                if (resultData != null)
                    throw new BusinessException(resultData?.Message ?? "API异常");
            }
        }
        return Task.CompletedTask;
    }
}


